package com.application.lucky.activity.me;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.application.lucky.Lucky;
import com.application.lucky.R;
import com.application.lucky.activity.LoginActivity;
import com.application.lucky.bean.jsonBean.BankItemBean;
import com.application.lucky.bean.sqliteBean.BankBean;
import com.application.lucky.gen.BankBeanDao;
import com.application.lucky.manager.UserManagers;
import com.application.lucky.request.CallBackEx;
import com.application.lucky.request.UserRequest;
import com.application.lucky.utils.ConnUtil;
import com.application.lucky.utils.Flog;
import com.application.lucky.utils.TopActivityManager;
import com.application.lucky.widget.TitlebarView;
import com.application.lucky.widget.dialog.TwoButtonDialog;
import com.application.mylibrary.base.BaseActivity;
import com.application.mylibrary.utils.SharedPreferencesUtil;
import com.application.mylibrary.utils.ToastUtils;
import com.baselib.libnetwork.net.libnetworkcomponent.BaseResponse;

import java.util.List;

public class AddBankActivity extends BaseActivity {
    private TitlebarView mTitleBar;
    private EditText mEdtName;
    private EditText mEdtAccountNumber;
    private EditText mEdtAccountName;
    private EditText mEdtAccountAddress;
    private boolean isInput;
    private BankBean bean;
    private String bankUserName;
    private String alreadyHaveBankNum;
    private TwoButtonDialog logoutDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();
    }

    @Override
    public void beforeInit() {
        isInput = getIntent().getBooleanExtra("is", true);
        bean = ((BankBean) getIntent().getParcelableExtra("bean"));
        bankUserName = getIntent().getStringExtra("real_name");
        alreadyHaveBankNum = getIntent().getStringExtra("already_bank_num");
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_bank;
    }

    private void initView() {
        mTitleBar = (TitlebarView) findViewById(R.id.title_bar);
        mTitleBar.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {
                finishAnim();
            }

            @Override
            public void rightClick() {
                showBottomDialog();
            }
        });

        mEdtName = (EditText) findViewById(R.id.edt_name);
        mEdtAccountNumber = (EditText) findViewById(R.id.edt_account_number);
        mEdtAccountName = (EditText) findViewById(R.id.edt_account_name);
        mEdtAccountAddress = (EditText) findViewById(R.id.edt_account_address);
        TextView bindCardBtn = (TextView) findViewById(R.id.button);
        if (bean != null && !isInput) {
            mEdtAccountName.setText(bean.accountNamw);
            mEdtAccountName.setFocusable(false);
            mEdtAccountName.setEnabled(false);
            mEdtName.setText(bean.name);
            mEdtName.setFocusable(false);
            mEdtName.setEnabled(false);
            mEdtAccountAddress.setText(bean.accountAddress);
            mEdtAccountAddress.setFocusable(false);
            mEdtAccountAddress.setEnabled(false);
            mEdtAccountNumber.setText(bean.num);
            mEdtAccountNumber.setFocusable(false);
            mEdtAccountNumber.setEnabled(false);
            bindCardBtn.setText(R.string.text_sure);
            bindCardBtn.setVisibility(View.INVISIBLE);
            mTitleBar.setRightDrawable(R.drawable.icon_chat_bar_more);
        } else if (!TextUtils.isEmpty(bankUserName)) {
            mEdtName.setText(bankUserName);
            mEdtName.setFocusable(false);
            mEdtName.setEnabled(false);
        }

//        mEdtName.setFocusable(isInput);
//        mEdtName.setFocusableInTouchMode(isInput);
//        mEdtAccountNumber.setFocusable(isInput);
//        mEdtAccountNumber.setFocusableInTouchMode(isInput);
//        mEdtAccountName.setFocusable(isInput);
//        mEdtAccountName.setFocusableInTouchMode(isInput);
//        mEdtAccountAddress.setFocusable(isInput);
//        mEdtAccountAddress.setFocusableInTouchMode(isInput);
        bindCardBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                commit();
            }
        });
    }

    private void commit() {
        final String name = mEdtName.getText().toString();
        if (TextUtils.isEmpty(name)) {
            ToastUtils.show("姓名不能为空！");
            return;
        }
        final String num = mEdtAccountNumber.getText().toString();
        if (TextUtils.isEmpty(num)) {
            ToastUtils.show("卡号不能为空!");
            return;
        }

        if (num.length() < 16) {
            ToastUtils.show("卡号长度不对!");
            return;
        }

        final String accountName = mEdtAccountName.getText().toString();
        if (TextUtils.isEmpty(accountName)) {
            ToastUtils.show("银行名称不能为空！");
            return;
        }
        final String address = mEdtAccountAddress.getText().toString();
        if (TextUtils.isEmpty(address)) {
            ToastUtils.show("开户行不能为空！");
            return;
        }

        new UserRequest().getAlreadyBindBank(new CallBackEx<BaseResponse<List<BankItemBean>>>() {
            @Override
            public void onFailed(int code) {
                Flog.d(TAG, "getAlreadyBindBank onFailed code:" + code);
            }

            @Override
            public void onSuccess(BaseResponse<List<BankItemBean>> listBaseResponse) {
                if (ConnUtil.isEmpty(listBaseResponse.dataInfo)) { // 没有已经绑定的卡
                    new UserRequest().bindCard(num, address, accountName, name, null, new CallBackEx<BaseResponse>() {
                        @Override
                        public void onFailed(int code) {
                            Flog.d(TAG, "bindCard onFailed code:" + code);
                        }

                        @Override
                        public void onSuccess(BaseResponse baseResponse) {
                            Flog.d(TAG, "bindCard onSuccess baseResponse:" + baseResponse);
                            BankBean bankBean = new BankBean();
                            bankBean.name = name;
                            bankBean.num = num;
                            bankBean.userId = UserManagers.getInstance().getUserId();
                            bankBean.accountNamw = accountName;
                            bankBean.accountAddress = address;

                            addBankInsert(bankBean);
                        }
                    });
                    return;
                }

                // 存在已经在绑定的卡
                List<BankItemBean> resBeanList = listBaseResponse.dataInfo;
                for (BankItemBean item : resBeanList) {
                    if (TextUtils.equals(item.bank, num)) {
                        ToastUtils.show("该银行卡号已经添加过了!");
                        return;
                    }
                }

                if (bean != null) {
                    new UserRequest().updateCard(String.valueOf(bean.getRequestId()), num, address, accountName, name, null, new CallBackEx<BaseResponse>() {
                        @Override
                        public void onFailed(int code) {
                            Flog.d(TAG, "bindCard onFailed code:" + code);
                        }

                        @Override
                        public void onSuccess(BaseResponse baseResponse) {
                            Flog.d(TAG, "updateCard onSuccess baseResponse:" + baseResponse);
                            BankBean bankBean = new BankBean();
                            bankBean.name = name;
                            bankBean.num = num;
                            bankBean.userId = UserManagers.getInstance().getUserId();
                            bankBean.accountNamw = accountName;
                            bankBean.accountAddress = address;

                            updateBank(bankBean);
                        }
                    });
                } else {
                    new UserRequest().bindCard(num, address, accountName, name, null, new CallBackEx<BaseResponse>() {
                        @Override
                        public void onFailed(int code) {
                            Flog.d(TAG, "bindCard onFailed code:" + code);
                        }

                        @Override
                        public void onSuccess(BaseResponse baseResponse) {
                            Flog.d(TAG, "bindCard onSuccess baseResponse:" + baseResponse);
                            BankBean bankBean = new BankBean();
                            bankBean.name = name;
                            bankBean.num = num;
                            bankBean.userId = UserManagers.getInstance().getUserId();
                            bankBean.accountNamw = accountName;
                            bankBean.accountAddress = address;

                            addBankInsert(bankBean);
                        }
                    });
                }
            }
        });
    }

    private void updateBank(BankBean bankBean) {
        BankBeanDao bankBeanDao = Lucky.getApplication().getDaoSession().getBankBeanDao();
        if (bankBeanDao != null) {
            bankBeanDao.update(bankBean);
        }
        finish();
    }

    private void addBankInsert(BankBean bankBean) {
        if (isInput) {
            Intent intent = new Intent(this, PerfectDataActivity.class);
            intent.putExtra("bean", bankBean);
            setResult(2, intent);
        }
        BankBeanDao bankBeanDao = Lucky.getApplication().getDaoSession().getBankBeanDao();
        bankBeanDao.insertOrReplace(bankBean);
        finish();
    }

    private void showBottomDialog() {
        if (logoutDialog != null && logoutDialog.isShowing()) {
            logoutDialog.dismiss();
            logoutDialog = null;
        }

        logoutDialog = new TwoButtonDialog.Build(AddBankActivity.this)
                .disMiss(true)
                .setMessage("确定解绑银行卡？")
                .setLeftButton("取消", null)
                .setRightButton("确定", new TwoButtonDialog.BaseDialogClickListener() {
                    @Override
                    public void click() {
                        logoutDialog.dismiss();

                        if (bean == null) {
                            Toast.makeText(AddBankActivity.this, "解绑失败", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        new UserRequest().unBindCard(String.valueOf(bean.getRequestId()), new CallBackEx<BaseResponse>() {
                            @Override
                            public void onFailed(int code) {
                                Toast.makeText(AddBankActivity.this, "解绑失败", Toast.LENGTH_SHORT).show();
                                Flog.d(TAG, "onFailed code:" + code);
                            }

                            @Override
                            public void onSuccess(BaseResponse jsonBean) {
                                Toast.makeText(AddBankActivity.this, "解绑成功", Toast.LENGTH_SHORT).show();
                                BankBeanDao bankBeanDao = Lucky.getApplication().getDaoSession().getBankBeanDao();
                                if (bankBeanDao != null) {
                                    bankBeanDao.delete(bean);
                                }
                                AddBankActivity.this.finish();
                            }
                        });
                    }
                }).create();
        logoutDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (logoutDialog != null && logoutDialog.isShowing()) {
            logoutDialog.dismiss();
            logoutDialog = null;
        }
    }
}
